package com.example.sunsg.okhttptest.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import com.breadtrip.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by sunsg on 16-5-5.
 */
public class CanvasDemo extends View{
    /**PATH线**/
    public static final int LINE_PATH = 0;
    /**正常画*/
    public static final int LINE_NOTMAL =1;
    /**折线图*/
    public static final int LINE_GRAPH = 2;
    /**画图片*/
    public static final int BITMAP_PAIT = 3;
    /**是否可以画*/
    private boolean mCanDraw;
    /**画哪一个*/
    private int mTypeDraw = -1;

    private int mHeight;
    private int mWidth;
    public CanvasDemo(Context context) {
        this(context,null);
    }

    public CanvasDemo(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CanvasDemo(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context){
        Log.i("test","init");
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.i("test","vvvvvvvvvvwidth = "+w +" height = "+h);
        mWidth = w;
        mHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(mCanDraw){
            switch (mTypeDraw){
                case LINE_PATH:
                    drawLine(canvas);
                    break;
                case LINE_NOTMAL:
                    drawNormal(canvas);
                break ;
                case LINE_GRAPH:
                    drawLineGraph(canvas);
                    break;
                case BITMAP_PAIT:
                    drawBitmap(canvas);
                    break;
            }
        }
    }

    /**path line start
     *
     * 用path画
     * **/
    private Paint mPaintLine;
    private Path mPathLine;
    private float mTextSize;
    public void drawLine(){
        mTextSize = TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics());
        mPaintLine = new Paint();
        mPaintLine.setColor(Color.RED);
        mPaintLine.setStrokeWidth(3);
        mPaintLine.setStyle(Paint.Style.STROKE);
        mPaintLine.setAntiAlias(true);
        mPaintLine.setDither(true);
        mPathLine = new Path();
        mPathLine.lineTo(300,300);
        mPaintLine.setTextSize(mTextSize);//设置文字大小
        mTypeDraw = LINE_PATH;
        mCanDraw = true;
        invalidate();
    }

    private void drawLine(Canvas canvas){
        canvas.drawPath(mPathLine,mPaintLine);
        mPathLine.moveTo(0,100);//移动到 （0，100）坐标点
        mPathLine.lineTo(300,300);//链接（0，100）和 （300，300）为点为一条直线
        mPathLine.lineTo(300,400);//链接 （300，300）和（300，400）为一条直线
        mPathLine.lineTo(0,400);
        mPathLine.lineTo(300,500);
        mPathLine.close();//链接足后的 lineto坐标点到 moveto坐标点为直线
        canvas.drawPath(mPathLine,mPaintLine);

        mPathLine.moveTo(400,400);
        mPathLine.quadTo(480,500,600,400);//二阶贝塞尔曲线（480，500）为控制点 （600，400）为终点 其实点为 原点（也就是moveto的点）
        canvas.drawPath(mPathLine,mPaintLine);

        mPathLine.moveTo(600,400);
        mPathLine.cubicTo(700,600,1000,400,1100,600);//三阶贝塞尔曲线前四个参数为 两个控制点的坐标 （p1x，p1y，p2x，p2y）足后俩个为终点的坐标点
        canvas.drawPath(mPathLine,mPaintLine);


        mPathLine.reset();
        mPathLine.moveTo(0,500);
        RectF ovel = new RectF(0,500,400,900);
        mPathLine.addArc(ovel,0,180);//在 ovel矩形中画个内切圆 addarc 不连接起始点
//        mPathLine.arcTo(ovel,0,359);//连接起始点
        canvas.drawPath(mPathLine,mPaintLine);
        canvas.drawRect(ovel,mPaintLine);//画矩形
        float textWidth = mPaintLine.measureText("中华");
        float offsetX = (float) (200*Math.PI/2 - textWidth/2);
        canvas.drawTextOnPath("中国",mPathLine,offsetX,80,mPaintLine);

        mPathLine.reset();
        mPathLine.moveTo(500,500);
        RectF rfoval = new RectF(500,500,900,900);
        mPathLine.addOval(rfoval, Path.Direction.CW);
        float textWidth1 = mPaintLine.measureText("中华人民共和国");
        float offsetX1 = (float) (2*200*Math.PI/2 - textWidth1/2);
        canvas.drawTextOnPath("中华人民共和国",mPathLine,offsetX1,0,mPaintLine);

//        mPathLine.reset();
//        mPathLine.moveTo(0,700);
//        mPathLine.addCircle(100,900,100, Path.Direction.CW);
//        canvas.drawPath(mPathLine,mPaintLine);
//
//        mPathLine.moveTo(300,800);
//        RectF roundF = new RectF(300,800,500,1000);
//        mPathLine.addRoundRect(roundF,30,30, Path.Direction.CW);
//        canvas.drawPath(mPathLine,mPaintLine);
    }

    /**path line end*/

    //================= path noarml start ====================
     /**
     *
     * 正常的画
     * */
    private Paint mPainCanvas;
    private RectF mRectfCanvas;
    public void drawNormal(){
        mPainCanvas = new Paint();
        mPainCanvas.setAntiAlias(true);
        mPainCanvas.setDither(true);
        mPainCanvas.setColor(0xff09edff);
        mRectfCanvas = new RectF(20,0,100,150);

        mTypeDraw = LINE_NOTMAL;
        mCanDraw = true;
        invalidate();
    }

    private void drawNormal(Canvas canvas){
        canvas.drawRect(mRectfCanvas,mPainCanvas);
        canvas.translate(100,0);
        canvas.drawRoundRect(mRectfCanvas,30,30,mPainCanvas);
        canvas.translate(100,0);
        canvas.drawArc(mRectfCanvas,0,90,false,mPainCanvas);
        canvas.translate(100,0);
        canvas.drawArc(mRectfCanvas,0,90,true,mPainCanvas);
        canvas.translate(100,0);
        canvas.drawOval(mRectfCanvas,mPainCanvas);
        canvas.translate(100,0);
        canvas.drawCircle(60,75,40,mPainCanvas);
    }

    //================= path noarml end ====================


    //================== 折线图 start =======================
    private int mGraphHeight;
    private int mScaleH = 100;
    private int mScaleWidth =40;
    private int mCenterY;
    private int mCenterX;
    private Paint mPaintGraph;
    private int mScalehCount;
    private int margenBottom = 40;
    private int margenLeft = 150;
    private String mGraphText;
    private float mGraphTextWidth;
    private float mGraphHeightOffset;
    private int mMaxSize;
    private List<Integer> mData;
    private Path mGraphPath;
    private static final int DELETE_TIME = 1000;
    private static final int WHAT_RECYCLE = 2;
    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            if(mData != null && mData.size() >= mMaxSize - 4){
                mData.remove(0);
                mData.add(new Random().nextInt(5) + 1 );
//                mPaintGraph.clearShadowLayer();
                mGraphPath.reset();
                invalidate();
            }
            addData();
        }
    };
    /***
     * 折线图
     */
    public void drawLineGraph(){
        mGraphHeight = mHeight;

        mScalehCount = mGraphHeight / mScaleH;
        mCenterY = mGraphHeight - margenBottom;
        mCenterX = margenLeft;

        mPaintGraph = new Paint();
        mPaintGraph.setAntiAlias(true);
        mPaintGraph.setDither(true);
        mPaintGraph.setColor(0xff000000);
        mPaintGraph.setTextSize(25);
        mPaintGraph.setStyle(Paint.Style.FILL);
        mGraphHeightOffset = mPaintGraph.measureText("M");

        mMaxSize = mWidth / mScaleWidth;
        mData = new ArrayList<>();
        for (int i = 0;i<mMaxSize - 4;i++){
            mData.add(new Random().nextInt(5) + 1 );
        }
        mGraphPath = new Path();
        mTypeDraw = LINE_GRAPH;
        mCanDraw = true;
        invalidate();
        addData();
    }


    private void drawLineGraph(Canvas canvas){

        mPaintGraph.setColor(Color.BLACK);
        canvas.drawLine(mCenterX,0,mCenterX-30,40,mPaintGraph);
        canvas.drawLine(mCenterX,0,mCenterX+30,40,mPaintGraph);
        canvas.translate(mCenterX,mCenterY - margenBottom);
        canvas.drawLine(0,0,0,-mCenterY,mPaintGraph);
        canvas.drawLine(0,0,mWidth,0,mPaintGraph);
        for (int i = 0; i < mScalehCount; i ++){
            //画每条刻度的横线
            if(i > 0){
                canvas.drawLine(0,-mScaleH*i,mScaleWidth,-mScaleH*i,mPaintGraph);
                mGraphText = i +" M";
                mGraphTextWidth = mPaintGraph.measureText(mGraphText);
                canvas.drawText(mGraphText,-mGraphTextWidth-50,-mScaleH*i +mGraphHeightOffset/2 ,mPaintGraph);
            }
        }

        if(mData.size() > 0){
            mPaintGraph.setColor(Color.BLUE);
            for (int j = 0;j<mData.size();j++){
                mGraphPath.lineTo(j*mScaleWidth,-mScaleH*mData.get(j));
            }
            mGraphPath.lineTo(mScaleWidth * (mData.size() - 1),0);
            canvas.drawPath(mGraphPath,mPaintGraph);

        }


//        mGraphPath.moveTo(0,0);
//        mGraphPath.lineTo(0,-5*mScaleH);
//        mGraphPath.lineTo(5*mScaleWidth,-5*mScaleH);
//        mGraphPath.lineTo(5*mScaleWidth,0);
//        canvas.drawPath(mGraphPath,mPaintGraph);


        Log.i("test","odrawwww");
    }

    private void addData(){
        mHandler.sendEmptyMessageDelayed(WHAT_RECYCLE,DELETE_TIME);
    }

    //===================折线图end===============


    //===================画图片start ===================

    private Paint mPaintBitmap;
    private Rect mSrcRect;
    private Rect mDesRect;
    private Bitmap mBitmap;
    public void drawBitmap(){
        mPaintBitmap = new Paint();
        BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.beauty);
        mBitmap = bitmapDrawable.getBitmap();
        int right = (mWidth - mBitmap.getWidth())/2;
        int bottom = (mHeight - mBitmap.getHeight())/2;
        mSrcRect = new Rect(0,0, mBitmap.getWidth(),mBitmap.getHeight()/2);
        mDesRect  = new Rect(right,bottom, right + mBitmap.getWidth(),bottom + mBitmap.getHeight()/2);
        mTypeDraw = BITMAP_PAIT;
        mCanDraw = true;
        invalidate();
    }

    private void drawBitmap(Canvas canvas){
        canvas.drawBitmap(mBitmap,mSrcRect,mDesRect,mPaintBitmap);
    }
    //===================画图片end ===================




}
